<template>
  <div class="rule-container">
    <div class="create-container">
      <el-button
        type="primary"
        @click="dialogVisible = true"
      >增加停车计费规则</el-button>
      <el-button @click="exportExcel">导出Excel</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="ruleList" style="width: 100%">
        <el-table-column type="index" label="序号" />
        <el-table-column label="计费规则编号" prop="ruleNumber" />
        <el-table-column label="计费规则名称" prop="ruleName" />
        <el-table-column label="免费时长(分钟)" prop="freeDuration" />
        <el-table-column label="收费上线(元)" prop="chargeCeiling" />
        <el-table-column label="计费方式" prop="chargeType">
          <template #default="scope">
            {{ formChargeType(scope.row.chargeType) }}
          </template>
        </el-table-column>
        <el-table-column label="计费规则" prop="ruleNameView" />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="scope">
            <el-button size="mini" type="text">编辑</el-button>
            <el-button size="mini" type="text">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="page-container">
        <el-pagination
          layout="total, prev, pager, next"
          :total="total"
          :page-size="params.pageSize"
          @current-change="pageChange"
        />
      </div>
    </div>

    <!-- 对话弹框 -->
    <el-dialog
      :visible="dialogVisible"
      width="680px"
      title="新增规则"
      @close="closeDialog"
    >
      <!-- 表单接口 -->
      <div class="form-container">
        <el-form
          ref="addForm"
          :model="addForm"
          :rules="addFormRules"
          label-position="top"
        >
          <el-form-item label="计费规则编号" prop="ruleNumber">
            <el-input v-model="addForm.ruleNumber" />
          </el-form-item>
          <el-form-item label="计费规则名称" prop="ruleName">
            <el-input v-model="addForm.ruleName" />
          </el-form-item>
          <el-form-item label="计费方式" prop="chargeType">
            <el-radio-group v-model="addForm.chargeType" size="small">
              <el-radio label="duration" border>时长收费</el-radio>
              <el-radio label="turn" border>按次收费</el-radio>
              <el-radio label="partition" border>分段收费</el-radio>
            </el-radio-group>
          </el-form-item>
          <div class="flex-container">
            <el-form-item label="免费时长">
              <el-input v-model="addForm.freeDuration" />
            </el-form-item>
            <el-form-item label="收费上限">
              <el-input v-model="addForm.chargeCeiling" />
            </el-form-item>
          </div>
          <el-form-item label="计费规则">
            <!-- 按时长收费区域 -->
            <div v-if="addForm.chargeType === 'duration'" class="duration">
              每
              <el-input v-model="addForm.durationTime" class="input-box" /> 小时
              <el-input v-model="addForm.durationPrice" class="input-box" /> 元
            </div>
            <!-- 按次收费区域 -->
            <div v-if="addForm.chargeType === 'turn'" class="turn">
              每次 <el-input v-model="addForm.turnPrice" class="input-box" /> 元
            </div>
            <!-- 按分段收费区域 -->
            <div v-if="addForm.chargeType === 'partition'" class="partition">
              <div class="item">
                <el-input
                  v-model="addForm.partitionFrameTime"
                  class="input-box"
                />小时内,每小时收费
                <el-input
                  v-model="addForm.partitionFramePrice"
                  class="input-box"
                />
                元
              </div>
              <div class="item">
                每增加
                <el-input
                  v-model="addForm.partitionIncreaseTime"
                  class="input-box"
                />小时,增加
                <el-input
                  v-model="addForm.partitionIncreasePrice"
                  class="input-box"
                />
                元
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button
          size="mini"
          type="primary"
          @click="confirmAdd"
        >确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getRuleListAPI, createRuleAPI } from '@/api/rules'
import { utils, writeFileXLSX } from 'xlsx'
export default {
  name: 'Building',
  data () {
    return {
      // 添加表单 对象
      addForm: {
        ruleNumber: '', // 计费规则编号
        ruleName: '', // 计费规则名称
        chargeType: 'duration', // 计费规则类型 duration / turn / partition
        chargeCeiling: null,
        freeDuration: null,
        // 时长计费独有字段
        durationTime: null, // 时长计费单位时间
        durationPrice: null, // 时长计费单位价格
        durationType: 'hour',
        // 按次收费独有字段
        turnPrice: null,
        // 分段计费独有字段
        partitionFrameTime: null, // 段内时间
        partitionFramePrice: null, // 段内费用
        partitionIncreaseTime: null, // 超出时间
        partitionIncreasePrice: null // 超出费为收费价钱
      },
      // // 计费规则校验规则对象
      addFormRules: {
        ruleNumber: [
          {
            required: true,
            message: '请输入规则编号',
            trigger: 'blur'
          }
        ],
        ruleName: [
          {
            required: true,
            message: '请输入规则名称',
            trigger: 'blur'
          }
        ],
        chargeType: [
          {
            required: true,
            message: '请选择收费类型',
            trigger: 'blur'
          }
        ]
      },
      // 是否显示
      dialogVisible: false,

      // ======================
      ruleList: [], // 规则列表
      // 请求参数
      params: {
        page: 1,
        pageSize: 5
      },
      // 规则总数
      total: 0
    }
  },
  mounted () {
    // 钩子 函数 自调用 列表函數
    this.getList()
  },
  methods: {
    confirmAdd () {
      this.$refs.validate(async isOK => {
        if (isOK) {
          await createRuleAPI(this.addForm)
          this.getList()
          this.dialogVisible = false
        }
      })
    },
    // 适配excel表格
    async exportExcel () {
      // 创建一个新的工作簿
      const workbook = utils.book_new()
      // 创建一个工作表 要求一个对象数组格式
      // const worksheet = utils.json_to_sheet([
      //   { name: '张三', age: 18 },
      //   { name: '李四', age: 28 }
      // ])

      // 1. 获取当前要导出的table数据
      const res = await getRuleListAPI(this.params)
      // 2. 按照需求调整数据的顺序
      const tableHeaderKeys = [
        'ruleNumber',
        'ruleName',
        'freeDuration',
        'chargeCeiling',
        'chargeType',
        'ruleNameView'
      ]
      const tableHeaderValues = [
        '计费规则编号',
        '计费规则名称',
        '免费时长(分钟)',
        '收费上线(元)',
        '计费方式',
        '计费规则'
      ]

      // 适配excel表格
      // 以excel表格的顺序调整后端数据
      const sheetData = res.data.rows.map(item => {
        const newObj = {} // 存放正确顺序的key-value 的新对象
        tableHeaderKeys.forEach(key => {
          if (key === 'chargeType') {
            newObj[key] = this.formChargeType(item[key])
          } else {
            newObj[key] = item[key]
          }
        })
        return newObj
      })
      const worksheet = utils.json_to_sheet(sheetData)

      // 把工作表添加到工作簿  Data为工作表名称
      utils.book_append_sheet(workbook, worksheet, 'Data')
      // 改写表头
      // utils.sheet_add_aoa(worksheet, [['姓名', '年龄']], { origin: 'A1' })
      utils.sheet_add_aoa(worksheet, [tableHeaderValues], { origin: 'A1' })
      // 导出方法进行导出
      writeFileXLSX(workbook, 'SheetJSVueAoO.xlsx')
    },
    // 适配付费状态
    formChargeType (chargeType) {
      const MAP = {
        duration: '时长收费',
        turn: '按次收费',
        partition: '分段收费'
      }
      return MAP[chargeType]
    },
    // 关闭弹窗
    closeDialog () {
      this.dialogVisible = false
    },
    // 获取列表函數
    async getList () {
      const res = await getRuleListAPI(this.params)
      this.ruleList = res.data.rows
      this.total = res.data.total
    },
    // 页码改变回调的函数
    pageChange (page) {
      this.params.page = page // 页码改变， 更新请求参数
      console.log(page)
      this.getList() // 重新調用列表函數
    }
  }
}
</script>

<style lang="scss" scoped>
.rule-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container {
  margin: 10px 0px;
}
.page-container {
  padding: 4px 0px;
  text-align: right;
}
.form-container {
  padding: 0px 80px;
}
</style>
